<template>
  <div class="design-editor-container">
    <!-- 简化后的编辑器布局 -->
    <div class="editor-main">
      <!-- 左侧工具栏 -->
      <div class="editor-sidebar" :class="{ 'collapsed': sidebarCollapsed }">
        <div class="sidebar-header">
          <h3>设计工具</h3>
          <button class="collapse-btn" @click="toggleSidebar">
            {{ sidebarCollapsed ? '›' : '‹' }}
          </button>
        </div>
        <div class="sidebar-content" v-if="!sidebarCollapsed">
          <!-- 工具选项卡 -->
          <div class="tool-tabs">
            <div class="tab" :class="{active: activeTab === 'template'}" @click="activeTab = 'template'">模板</div>
            <div class="tab" :class="{active: activeTab === 'elements'}" @click="activeTab = 'elements'">元素</div>
            <div class="tab" :class="{active: activeTab === 'layers'}" @click="activeTab = 'layers'">图层</div>
          </div>
          
          <!-- 工具内容区 -->
          <div class="tool-content">
            <div v-if="activeTab === 'template'">
              <button class="tool-btn" @click="createBlankCanvas">空白画布</button>
              <button class="tool-btn" @click="addTestRect">添加测试图形</button>
            </div>
            <div v-else-if="activeTab === 'elements'">
              <button class="tool-btn" @click="addNewRect">添加矩形</button>
              <button class="tool-btn" @click="addNewCircle">添加圆形</button>
            </div>
            <div v-else-if="activeTab === 'layers'">
              <p>图层管理面板</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间画布区域 -->
      <div class="canvas-area">
        <!-- 简化的工具栏 -->
        <div class="canvas-toolbar">
          <div class="tool-group">
            <button class="tool-btn" @click="zoomIn" title="放大">
              <i class="fas fa-search-plus"></i>
            </button>
            <span class="zoom-level">{{ Math.round((zoomLevel || 1) * 100) }}%</span>
            <button class="tool-btn" @click="zoomOut" title="缩小">
              <i class="fas fa-search-minus"></i>
            </button>
            <button class="tool-btn" @click="originalSize" title="原始大小">
              <i class="fas fa-expand"></i>
            </button>
            <button class="tool-btn" @click="centerCanvas" title="居中画布">
              <i class="fas fa-crosshairs"></i>
            </button>
          </div>
        </div>
        
        <!-- 画布容器 - 确保画布居中显示 -->
        <div class="canvas-wrapper">
          <FabricEditor ref="fabricEditorRef" class="fabric-editor" />
          <div class="canvas-info" v-if="showInfo">
            <div v-if="canvas">
              <p>画布大小: {{ workspaceWidth }} x {{ workspaceHeight }}</p>
              <p>缩放: {{ zoomLevel.toFixed(2) }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="properties-panel" v-if="showProperties">
        <div class="panel-header">
          <h3>属性</h3>
          <button class="close-btn" @click="showProperties = false">×</button>
        </div>
        <div class="panel-content">
          <div v-if="selectedObject">
            <div class="property-group">
              <h4>位置与大小</h4>
              <div class="property-row">
                <label>宽度:</label>
                <input type="number" v-model="canvasWidth" @change="updateCanvasSize" />
              </div>
              <div class="property-row">
                <label>高度:</label>
                <input type="number" v-model="canvasHeight" @change="updateCanvasSize" />
              </div>
            </div>
          </div>
          <div v-else>
            <p>请选择一个对象</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, computed } from 'vue';
import FabricEditor from '../components/FabricEditor.vue';
// 导入fabric库
// @ts-ignore
import * as fabricModule from 'fabric';
const fabric = fabricModule.fabric || fabricModule;

// 状态
const activeTab = ref('template');
const sidebarCollapsed = ref(false);
const showProperties = ref(true);
const showInfo = ref(true);

// 画布引用
const fabricEditorRef = ref<InstanceType<typeof FabricEditor> | null>(null);
const canvas = ref<any>(null);

// 画布设置
const workspaceWidth = ref(800);
const workspaceHeight = ref(600);
const zoomLevel = ref(1);
const selectedObject = ref<any>(null);

// 用于属性面板的临时值
const canvasWidth = ref(workspaceWidth.value);
const canvasHeight = ref(workspaceHeight.value);

// resize防抖计时器
let resizeTimer: number | null = null;

// 初始化画布
function initCanvas() {
  if (!fabricEditorRef.value) {
    console.error('FabricEditor组件引用不存在');
    return;
  }
  
  try {
    // 获取canvas实例
    canvas.value = fabricEditorRef.value.canvas.value;
    
    if (!canvas.value) {
      console.error('无法获取FabricEditor画布实例');
      return;
    }
    
    console.log('成功获取FabricEditor画布实例');
    
    // 设置工作区大小
    fabricEditorRef.value.setCanvasSize(workspaceWidth.value, workspaceHeight.value);
    
    // 更新当前缩放比例
    zoomLevel.value = canvas.value.getZoom();
    
    // 如果需要居中画布
    centerCanvas();
    
    console.log('画布初始化完成');
  } catch (err) {
    console.error('初始化画布时发生错误:', err);
  }
}

// 居中画布
function centerCanvas() {
  if (!fabricEditorRef.value) {
    console.error('FabricEditor组件引用不存在');
    return;
  }
  
  fabricEditorRef.value.centerCanvas();
  
  if (canvas.value) {
    zoomLevel.value = canvas.value.getZoom();
  }
  
  console.log('画布已居中显示');
}

// 放大
function zoomIn() {
  if (!fabricEditorRef.value) return;
  
  fabricEditorRef.value.zoomIn();
  
  if (canvas.value) {
    zoomLevel.value = canvas.value.getZoom();
  }
}

// 缩小
function zoomOut() {
  if (!fabricEditorRef.value) return;
  
  fabricEditorRef.value.zoomOut();
  
  if (canvas.value) {
    zoomLevel.value = canvas.value.getZoom();
  }
}

// 原始大小
function originalSize() {
  if (!fabricEditorRef.value) return;
  
  fabricEditorRef.value.zoomToActualSize();
  
  if (canvas.value) {
    zoomLevel.value = canvas.value.getZoom();
  }
}

// 切换侧边栏
function toggleSidebar() {
  sidebarCollapsed.value = !sidebarCollapsed.value;
}

// 创建空白画布
function createBlankCanvas() {
  if (!canvas.value) return;
  
  canvas.value.clear();
  
  if (fabricEditorRef.value) {
    fabricEditorRef.value.setCanvasSize(workspaceWidth.value, workspaceHeight.value);
  }
  
  // 重新居中
  centerCanvas();
}

// 添加测试图形
function addTestRect() {
  if (!fabricEditorRef.value) return;
  
  fabricEditorRef.value.addTestRectangle();
}

// 添加矩形
function addNewRect() {
  if (!canvas.value) return;
  
  const rect = new fabric.Rect({
    left: workspaceWidth.value / 2 - 50,
    top: workspaceHeight.value / 2 - 50,
    width: 100,
    height: 100,
    fill: 'rgba(0,123,255,0.5)',
    stroke: '#007bff',
    strokeWidth: 1
  });
  
  canvas.value.add(rect);
  canvas.value.setActiveObject(rect);
  canvas.value.renderAll();
}

// 添加圆形
function addNewCircle() {
  if (!canvas.value) return;
  
  const circle = new fabric.Circle({
    left: workspaceWidth.value / 2 - 50,
    top: workspaceHeight.value / 2 - 50,
    radius: 50,
    fill: 'rgba(220,53,69,0.5)',
    stroke: '#dc3545',
    strokeWidth: 1
  });
  
  canvas.value.add(circle);
  canvas.value.setActiveObject(circle);
  canvas.value.renderAll();
}

// 更新画布大小
function updateCanvasSize() {
  if (!fabricEditorRef.value) return;
  
  workspaceWidth.value = canvasWidth.value;
  workspaceHeight.value = canvasHeight.value;
  
  fabricEditorRef.value.setCanvasSize(workspaceWidth.value, workspaceHeight.value);
  centerCanvas();
}

// 处理窗口大小变化
function handleResize() {
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  
  resizeTimer = window.setTimeout(() => {
    console.log('窗口大小变化，调整画布大小');
    if (fabricEditorRef.value) {
      centerCanvas();
    }
  }, 200);
}

// 生命周期钩子
onMounted(() => {
  console.log('SimpleEditorView组件已挂载');
  
  // 确保在DOM完全渲染后初始化Canvas
  nextTick(() => {
    console.log('DOM已更新，开始初始化Canvas');
    initCanvas();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  // 清理资源
  if (canvas.value) {
    canvas.value.dispose();
    canvas.value = null;
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  // 清除计时器
  if (resizeTimer) {
    clearTimeout(resizeTimer);
    resizeTimer = null;
  }
});

defineExpose({
  canvas,
  fabricEditorRef,
  centerCanvas,
  zoomIn,
  zoomOut,
  originalSize
});
</script>

<style scoped>
.design-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.editor-main {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

/* 侧边栏样式 */
.editor-sidebar {
  width: 250px;
  background-color: #f8f9fa;
  border-right: 1px solid #e0e0e0;
  height: 100%;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
}

.editor-sidebar.collapsed {
  width: 50px;
}

.sidebar-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.collapse-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
}

.tool-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
}

.tab {
  padding: 10px 15px;
  cursor: pointer;
  user-select: none;
}

.tab.active {
  border-bottom: 2px solid #007bff;
  color: #007bff;
}

.tool-content {
  padding: 15px;
}

.tool-btn {
  display: block;
  width: 100%;
  padding: 8px 12px;
  margin-bottom: 8px;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  text-align: left;
}

.tool-btn:hover {
  background-color: #f0f0f0;
}

/* 画布区域样式 */
.canvas-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f0f0f0;
  position: relative;
}

.canvas-toolbar {
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.tool-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.canvas-wrapper {
  flex: 1;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e9ecef;
}

.fabric-editor {
  width: 100%;
  height: 100%;
}

.canvas-info {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0,0,0,0.6);
  color: white;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
}

/* 属性面板样式 */
.properties-panel {
  width: 280px;
  background-color: #fff;
  border-left: 1px solid #e0e0e0;
  height: 100%;
  overflow-y: auto;
}

.panel-header {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
}

.panel-content {
  padding: 15px;
}

.property-group {
  margin-bottom: 20px;
}

.property-group h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.property-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.property-row label {
  width: 80px;
  color: #333;
}

.property-row input[type="number"] {
  width: 80px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.zoom-level {
  display: inline-block;
  min-width: 45px;
  text-align: center;
}
</style> 